<?php
namespace Report\Controller;
use Think\Controller;
class CommissionReportController extends Controller {
    public function getRebate($arr,$agent){//获取返佣数据的父级
        foreach($arr as $k => $v){
            if($v['user_id']==$agent){
                if($v['position']==1){
                    return $this->getRebate($arr,$v['user_recommend']);
                }else{
                    return array('user_id'=>$v['user_id'],'group'=>$v['group'],'position'=>$v['position']);
                }
            }
        }
    }
    public function detail(){//佣金明细
        $this->display();
    }

    public function searchDetail1(){//佣金明细-1层佣金
        $this->display();
    }

    public function searchDetail2(){//佣金明细-2层佣金
        $this->display();
    }

    public function searchDetail3(){//佣金明细-3层佣金
        $this->display();
    }



    public function summary(){//佣金汇总
        $this->display();
    }

    public function searchSummary1(){//佣金汇总-1层佣金
        $from=I('post.from') ? I('post.from') : die('请选择开始时间，<a href="javascript:history.back(-1)">点击返回</a>');
        $to=I('post.to') ? I('post.to') : die('请选择结束时间，<a href="javascript:history.back(-1)">点击返回</a>');
        $type=I('post.type') ? I('post.type') : die('请选择按账号查询或组别查询，<a href="javascript:history.back(-1)">点击返回</a>');
        $userModel=M('user');
        $use_where='(user_role=1) ';
        if($type==1){//按账号查询
            $logins=I('post.keywords') ? I('post.keywords') : '%';
            if($logins!='%'){
                $use_where.=' and (user_id in ('.$logins.'))';
            }
        }else{//按组别查询
            $groups=I('post.keywords') ? I('post.keywords') : '%';
            if($groups!='%'){
                $groups=str_replace(",","','",$groups);//组别是字符串，所以需要加引号
                $use_where.=' and (`group` in (\''.$groups.'\'))';
            }
        }
        $users=$userModel->field('user_id')->where($use_where)->select();
        $login=[];
        foreach ($users as $ke => $va){
            $login[]=$va['user_id'];
        }
        $section=C('section');//获取号段
        $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,sum(VOLUME)')
            ->where('(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].') and (CLOSE_TIME between \''.$from.'\' and \''.$to.' 23:59:59\') and (right(SYMBOL,2) = \'bo\')')
            ->group('LOGIN')->select();
        if(empty($reoups)){
            die('未找到交易记录，<a href="javascript:history.back(-1)">点击返回</a>');
        }
        $group=M('mt4_groups')->field('mt4_group,ratio')->select();
        $ratio=[];//每个组别的佣金比率
        foreach ($group as $k => $v){
            $ratio[$v['mt4_group']]=$v['ratio'];
        }
        //print_r($reoups);die;
        $rebateData=[];//最终需要返佣的数据
        $userAll=M('user')->field('user_id,user_recommend,group,position')->where('user_role=1')->select();
        $allUser=[];
        foreach ($userAll as $k => $v){
            $allUser[$v['user_id']]=$v;
        }
        foreach ($reoups as $k => $v){//获取自己的佣金返给谁
            if(!empty($allUser[$v['login']]) && ($allUser[$v['login']]['user_recommend']!=0)){
                $v['ratio']=$ratio[$allUser[$v['login']]['group']];
                $v['parent']=$this->getRebate($userAll,$allUser[$v['login']]['user_recommend']);
                if(!empty($v['parent'])){//剔除没有父级的数据，防止无用循环
                    $v['money']=round($ratio[$v['parent']['group']]*intval($v['sum(volume)']/100),2);
                    if($v['money']!=0){$rebateData[]=$v;}//剔除金额为0的数据，防止无用循环
                }
            }
        }
        print_r($rebateData);die;
        if(empty($rebateData)){
            die('没有相关佣金信息，<a href="javascript:history.back(-1)">点击返回</a>');
        }else{
            $list=[];
            foreach ($rebateData as $k => $v){
                if(in_array($v['parent']['user_id'],$login)){
                    $list[]=array(
                        'login'=>$v['login'],//交易用户
                        'agent'=>$v['parent']['user_id'],//受益人
                        'group'=>$v['parent']['group'],//受益人组别
                        'money'=>$v['money'],//佣金金额
                        'volume'=>intval($v['sum(volume)']/100)//交易手数
                    );
                }
            }
            $csv=new \Think\Csv();
            $csv_title=array('交易用户','受益用户','受益用户组别','佣金金额','交易量');
            $csv->put_csv($list,$csv_title);
        }
    }

    public function getRebateParents($data,$user_recommend,$position,$arr){//获取IB返佣数据的父级
        foreach($data as $k => $v){
            if($v['user_id']==$user_recommend){
                if($v['position']>1){
                    if($v['position']>=$position){
                        $arr[]=array('user_id'=>$v['user_id'],'position'=>$v['position'],'group'=>$v['group']);
                        unset($data[$k]);
                        $arr=$this->getRebateParents($data,$v['user_recommend'],$v['position'],$arr);
                    }else{
                        unset($data[$k]);
                        $arr=$this->getRebateParents($data,$v['user_recommend'],$position,$arr);
                    }
                }else{
                    unset($data[$k]);
                    $arr=$this->getRebateParents($data,$v['user_recommend'],$position,$arr);
                }
            }
        }
        return $arr;
    }

    public function searchSummary2(){//佣金汇总-2层佣金
        $from=I('post.from') ? I('post.from') : die('请选择开始时间，<a href="javascript:history.back(-1)">点击返回</a>');
        $to=I('post.to') ? I('post.to') : die('请选择结束时间，<a href="javascript:history.back(-1)">点击返回</a>');
        $type=I('post.type') ? I('post.type') : die('请选择按账号查询或组别查询，<a href="javascript:history.back(-1)">点击返回</a>');
        set_time_limit(120);//程序执行时间
        $userModel=M('user');
        $use_where='(user_role=1)';
        if($type==1){//按账号查询
            $logins=I('post.keywords') ? I('post.keywords') : '%';
            if($logins!='%'){
                $use_where.=' and (user_id in ('.$logins.'))';
            }
        }else{//按组别查询
            $groups=I('post.keywords') ? I('post.keywords') : '%';
            if($groups!='%'){
                $groups=str_replace(",","','",$groups);//组别是字符串，所以需要加引号
                $use_where.=' and (`group` in (\''.$groups.'\'))';
            }
        }
        $users=$userModel->field('user_id')->where($use_where)->select();
        $login=[];
        foreach ($users as $ke => $va){
            $login[]=$va['user_id'];
        }
        $section=C('section');//获取号段
        $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,sum(VOLUME)')
        ->where('(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].') and (CLOSE_TIME between \''.$from.'\' and \''.$to.' 23:59:59\') and (right(SYMBOL,2) = \'bo\')')
            ->group('LOGIN')->select();
        if(empty($reoups)){
            die('未找到交易记录，<a href="javascript:history.back(-1)">点击返回</a>');
        }
        $hasTradesUser=[];//有交易的用户信息
        $userAll=M('user')->field('user_id,user_recommend,group,position')->where('user_role=1')->select();
        $allUser=[];
        foreach ($userAll as $k => $v){
            $allUser[$v['user_id']]=$v;
        }
        foreach($reoups as $k => $v){
            if(!empty($allUser[$v['login']]) && ($allUser[$v['login']]['user_recommend']!=0)){
                $v['user_recommend']=$allUser[$v['login']]['user_recommend'];
                $v['volume']=intval($v['sum(volume)']/100);
                $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                $hasTradesUser[]=$v;
            }
        }
        $rebateData=[];//最终需要返佣的数据-明细
        foreach ($hasTradesUser as $k => $v){
            $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
            if(!empty($parents)){
                $parents2=$parents;
                foreach($parents2 as $ke => $va){
                    $flag=0;
                    foreach($parents as $key => $val){
                        if($va['position']==$val['position']){
                            $flag++;
                            if($flag>2){
                                unset($parents[$key]);
                            }
                        }
                    }
                }
                $v['parents']=$parents;//筛选出有返佣父级的数据
                $rebateData[]=$v;
            }
        }
        if(empty($rebateData)){die('今日无佣金发放信息，<a href="javascript:history.back(-1)">点击返回</a>');}
        $position=M('position')->field('id,ratio')->select();
        $pos=[];
        foreach($position as $k => $v){
            $pos[$v['id']]=$v['ratio'];
        }
        foreach ($rebateData as $k => $v){
            foreach ($v['parents'] as $ke => $va){
                $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                if($ke>0){
                    $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                    if($ratio>0){
                        $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                    }else if($ratio==0){
                        $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=0;
                    }
                }else{
                    $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                }
            }
        }
        print_r($rebateData);
        if(empty($rebateData)){
            die('没有相关佣金信息，<a href="javascript:history.back(-1)">点击返回</a>');
        }else{
            $list=[];
            foreach ($rebateData as $k => $v){
                foreach ($v['parents'] as $key => $val){
                    if(in_array($val['user_id'],$login)){
                        $list[]=array(
                            'login'=>$v['login'],//交易用户
                            'agent'=>$val['user_id'],//受益人
                            'group'=>$val['group'],//受益人组别
                            'money'=>$val['money'],//佣金金额
                            'volume'=>$v['volume']//交易手数
                        );
                    }
                }
            }
        }
        $csv=new \Think\Csv();
        $csv_title=array('交易用户','受益用户','受益用户组别','佣金金额','交易量');
        $csv->put_csv($list,$csv_title);
    }

    public function searchSummary3(){//佣金汇总-3层佣金
        $from=I('post.from') ? I('post.from') : die('请选择开始时间，<a href="javascript:history.back(-1)">点击返回</a>');
        $to=I('post.to') ? I('post.to') : die('请选择结束时间，<a href="javascript:history.back(-1)">点击返回</a>');
        $type=I('post.type') ? I('post.type') : die('请选择按账号查询或组别查询，<a href="javascript:history.back(-1)">点击返回</a>');
        set_time_limit(120);//程序执行时间
        $userModel=M('user');
        $use_where='(user_role=1)';
        if($type==1){//按账号查询
            $logins=I('post.keywords') ? I('post.keywords') : '%';
            if($logins!='%'){
                $use_where.=' and (user_id in ('.$logins.'))';
            }
        }else{//按组别查询
            $groups=I('post.keywords') ? I('post.keywords') : '%';
            if($groups!='%'){
                $groups=str_replace(",","','",$groups);//组别是字符串，所以需要加引号
                $use_where.=' and (`group` in (\''.$groups.'\'))';
            }
        }
        $users=$userModel->field('user_id')->where($use_where)->select();
        $login=[];
        foreach ($users as $ke => $va){
            $login[]=$va['user_id'];
        }
		
        $section=C('section');//获取号段
        $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,SYMBOL,sum(VOLUME)')
            ->where('(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].') and (CLOSE_TIME between \''.$from.'\' and \''.$to.' 23:59:59\')')->group('LOGIN,SYMBOL')->select();
        if(empty($reoups)){
            die('未找到交易记录，<a href="javascript:history.back(-1)">点击返回</a>');
        }
        $hasTradesUser=[];//有交易的用户信息
        $userAll=M('user')->field('user_id,user_recommend,group,position')->where('user_role=1')->select();
        $allUser=[];
        foreach ($userAll as $k => $v){
            $allUser[$v['user_id']]=$v;
        }
        foreach($reoups as $k => $v){
            if(!empty($allUser[$v['login']]) && ($allUser[$v['login']]['user_recommend']!=0)){
                $v['user_recommend']=$allUser[$v['login']]['user_recommend'];
                $v['volume']=round($v['sum(volume)']/100,2);
                $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                $hasTradesUser[]=$v;
            }
        }
        //品种点差
        $spreadData=M('symbol_spread')->field('id,symbol,spread')->select();
        $spread=[];
        foreach($spreadData as $k => $v){
            $spread[$v['symbol']]=$v['spread'];
        }
        $rebateData=[];//最终需要返佣的数据-明细
        foreach ($hasTradesUser as $k => $v){
            $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
            if(!empty($parents)){
                $parents2=$parents;
                foreach($parents2 as $ke => $va){
                    $flag=0;
                    foreach($parents as $key => $val){
                        if($va['position']==$val['position']){
                            $flag++;
                            if($flag>2){
                                unset($parents[$key]);
                            }
                        }
                    }
                }
                $v['spread']=$spread[$v['symbol']];
                $v['parents']=$parents;//筛选出有返佣父级的数据
                $rebateData[]=$v;
            }
        }
        if(empty($rebateData)){die('今日无佣金需要发放，<a href="javascript:history.back(-1)">点击返回</a>');}
        $position=M('position')->field('id,ratio,user_position,ratio_foreign')->select();
        $pos=[];//返佣比率
        $foreign=[];//外用比率
		$user_position=[];
        foreach($position as $k => $v){
            $pos[$v['id']]=$v['ratio'];
			$user_position[$v['id']]=$v['user_position'];
            $foreign[$v['id']]=$v['ratio_foreign'];
        }
        foreach ($rebateData as $k => $v){
            if(substr($v['symbol'],-2)=='bo'){
                foreach ($v['parents'] as $ke => $va){
                    $parent_arr[]=$va['user_id'];
                    $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                    if($ke>0){
                        $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                        if($ratio>0){
                            $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                        }else if($ratio==0){
                            $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                        }else{
                            $rebateData[$k]['parents'][$ke]['money']=0;
                        }
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                    }
                }
            }else{
                foreach ($v['parents'] as $ke => $va){
                    $parent_arr[]=$va['user_id'];
                    $rebateData[$k]['parents'][$ke]['ratio']=$foreign[$va['position']];
                    if($ke>0){
                        $ratio=$foreign[$va['position']]-$foreign[$v['parents'][$ke-1]['position']];
                        if($ratio>0){
                            $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume']*$v['spread'];
                        }else if($ratio==0){
                            $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                        }else{
                            $rebateData[$k]['parents'][$ke]['money']=0;
                        }
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=$foreign[$va['position']]*$v['volume']*$v['spread'];
                    }
                }
            }
        }
        //print_r($rebateData);die;
        if(empty($rebateData)){
            die('没有相关佣金信息，<a href="javascript:history.back(-1)">点击返回</a>');
        }else{
            $list=[];
            foreach ($rebateData as $k => $v){
                foreach ($v['parents'] as $key => $val){
                    if(in_array($val['user_id'],$login)){
                        $list[]=array(
                            'login'=>$v['login'],//交易用户
                            'agent'=>$val['user_id'].' ('.$user_position[$val['position']].')',//受益人
                            'group'=>$val['group'],//受益人组别
                            'money'=>$val['money'],//佣金金额
                            'volume'=>$v['volume'],//交易手数
							'symbol'=>$v['symbol']
                        );
                    }
                }
            }
        }
        $csv=new \Think\Csv();
        $csv_title=array('交易用户','受益用户','受益用户组别','佣金金额','交易量','交易品种');
        $csv->put_csv($list,$csv_title);
    }



    public function grantList(){//佣金发放
        $this->display();
    }

    public function searchGrant(){//佣金发放
        $from=I('post.from') ? I('post.from') : die('请选择开始时间，<a href="javascript:history.back(-1)">点击返回</a>');
        $to=I('post.to') ? I('post.to') : die('请选择结束时间，<a href="javascript:history.back(-1)">点击返回</a>');
        $type=I('post.type') ? I('post.type') : die('请选择按账号查询或组别查询，<a href="javascript:history.back(-1)">点击返回</a>');
        $userModel=M('user');
        $use_where='(user_role=1)';
        if($type==1){//按账号查询
            $logins=I('post.keywords') ? I('post.keywords') : '%';
            if($logins!='%'){
                $use_where.=' and (user_id in ('.$logins.'))';
            }
        }else{//按组别查询
            $groups=I('post.keywords') ? I('post.keywords') : '%';
            if($groups!='%'){
                $groups=str_replace(",","','",$groups);//组别是字符串，所以需要加引号
                $use_where.=' and (`group` in (\''.$groups.'\'))';
            }
        }
        $users=$userModel->field('user_id')->where($use_where)->select();
        $login=[];
        foreach ($users as $ke => $va){
            $login[]=$va['user_id'];
        }
        //查询佣金发放记录
        $model=M('mt4_trades','','DB_CONFIG2');
        $where='(CMD = 6) and (LOGIN in ('.implode(',',$login).')) and (CLOSE_TIME between \''.$from.'\' and \''.$to.' 23:59:59\') and (COMMENT like \'CommBo%\')';
        $list=$model->field('TICKET,LOGIN,CMD,CLOSE_TIME,PROFIT,COMMENT')->where($where)->select();
        $data=[];
        foreach ($list as $k => $v){
            $data[]=array(
                'ticket'=>$v['ticket'],
                'login'=>$v['login'],
                'cmd'=>$v['cmd']==6 ? 'Balance' : $v['cmd'],
                'close_time'=>$v['close_time'],
                'profit'=>round($v['profit'],2),
                'comment'=>$v['comment']
            );
        }
        $csv=new \Think\Csv();
        $csv_title=array('交易号','MT4','交易类型','时间','收益','注释');
        $csv->put_csv($list,$csv_title);
    }
}